package com.tianyang.yukuaifuzs.base;

import android.app.Activity;
import android.content.Context;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;

import com.tianyang.yukuaifuzs.R;
import com.tianyang.yukuaifuzs.business.main.view.MainActivity;
import com.tianyang.yukuaifuzs.common.cache.CacheManage;
import com.tianyang.yukuaifuzs.common.cache.CacheModel;
import com.tianyang.yukuaifuzs.common.view.RippleLoadingDialog;
import com.tianyang.yukuaifuzs.jump.eventbus.OfflineEvent;
import com.tianyang.yukuaifuzs.module.immersionbar.ImmersionBar;
import com.tianyang.yukuaifuzs.module.immersionbar.OSUtils;
import com.tianyang.yukuaifuzs.rxservice.RxError;
import com.tianyang.yukuaifuzs.utils.AppContextUtil;
import com.tianyang.yukuaifuzs.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import butterknife.ButterKnife;

/**
 * Description：FragmentActivity基类
 */

public abstract class BaseFragmentActivity extends PermissionActivity {

    private final String TAG = this.getClass().getName();

    private RippleLoadingDialog loadingDialog;

    protected Context mContext;

    protected Bundle savedInstanceState;

    protected ImmersionBar mImmersionBar;

    private String NAVIGATIONBAR_IS_MIN = "navigationbar_is_min";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(null);
        mContext = this;
        setContentView(getLayoutResID());
        this.savedInstanceState = savedInstanceState;
        ButterKnife.bind(this);
        AppContextUtil.pushActivity(this);
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }
        initView();
        setListener();
        initData();
        if (hasBindEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        CacheManage.getInstance().saveCache(CacheModel.ISFOREGROUND, true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        CacheManage.getInstance().saveCache(CacheModel.ISFOREGROUND, false);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoadingDialog();
        AppContextUtil.popActivity(this);
        if (hasBindEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        //解决华为emui3.0与3.1手机手动隐藏底部导航栏时，导航栏背景色未被隐藏的问题
        if (OSUtils.isEMUI3_1()) {
            //第一种
            getContentResolver().registerContentObserver(Settings.System.getUriFor
                    (NAVIGATIONBAR_IS_MIN), true, mNavigationStatusObserver);
            //第二种,禁止对导航栏的设置
            //mImmersionBar.navigationBarEnable(false).init();
        }
        mImmersionBar.statusBarColorTransformEnable(true)
                .statusBarView(R.id.topView)
                .statusBarDarkFont(true, 0.5f)
                .statusBarColor(R.color.white)
                .fullScreen(false)
                .init();
    }

    private ContentObserver mNavigationStatusObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            try {
                int navigationBarIsMin = Settings.System.getInt(getContentResolver(),
                        NAVIGATIONBAR_IS_MIN, 0);
                mImmersionBar = ImmersionBar.with((Activity) mContext);
                if (navigationBarIsMin == 1) {
                    //导航键隐藏了
                    mImmersionBar.transparentNavigationBar().init();
                } else {
                    //导航键显示了
                    mImmersionBar.navigationBarColor(R.color.c_2b2e33) //隐藏前导航栏的颜色
                            .fullScreen(false)
                            .init();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
    }

    protected abstract int getLayoutResID();

    protected void initView() {}

    protected void initData() {}

    protected void setListener() {}

    /**
     * 当前页面是否有EventBus。 默认为false
     *
     * @return
     */
    protected abstract boolean hasBindEventBus();

    /**
     * 显示加载数据进度条
     */
    public void showLoadingDialog(boolean cancelable) {
        showLoadingDialog(cancelable, "正在加载中...");
    }

    /**
     * 显示加载数据进度条
     */
    public void showLoadingDialog(boolean cancelable, String content) {
        if (loadingDialog == null) {
            loadingDialog = new RippleLoadingDialog(this);
        } else {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        }
        loadingDialog.setCancelable(cancelable);
        if (!TextUtils.isEmpty(content));
        loadingDialog.title(content);
        loadingDialog.show();
    }

    /**
     * 取消正在显示的dialog
     */
    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    /**
     * 接口回调error提示错误信息
     * @param e
     */
    public void showErrorText(Throwable e) {
        if (e instanceof RxError) {
            RxError error = (RxError) e;
            if (TextUtils.equals(RxError.ERROR_OFFLINE, error.errorCode)) {
                AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
                EventBus.getDefault().post(new OfflineEvent("你的账号已在另外一台设备登录，请重新登录!"));
            } else if (TextUtils.equals(RxError.ERROR_UNKNOWN, error.errorCode)) {
                ToastUtil.showTextViewPrompt("网络异常!");
            } else {
                ToastUtil.showTextViewPrompt(error.getMessage());
            }
        } else if (e instanceof SocketTimeoutException) {
            ToastUtil.showTextViewPrompt("网络连接超时!");
        } else if (e instanceof ConnectException) {
            ToastUtil.showTextViewPrompt("网络连接异常!");
        } else {
            ToastUtil.showTextViewPrompt("接口异常!");
        }
    }
}
